/**********************************************
** @Author: phy
** @Date:   2017-12-12 14:17:37
** @Last Modified by:   phy
***********************************************/
package controllers

import (
	"strconv"
	"os"
	"github.com/xuri/excelize"
	"fmt"
	//"strconv"
	//"strings"
	"time"

	"github.com/astaxie/beego"
	"WebAdminSys/libs"
	"WebAdminSys/models"

)

type SysRoomconfController struct {
	BaseController
}

func (self *SysRoomconfController) List() {
	self.Data["pageTitle"] = "房间配置"
	//self.Ctx.WriteString("MangeAdminController.List")
	gmlos := fmt.Sprintf("进入【%s】界面",self.Data["pageTitle"])
	self.AddOperationLog(gmlos,1)
	self.display()
}


func (self *SysRoomconfController) AjaxDel() {
	iType,_  := self.GetInt("Del_Type",0)
	if iType == 1 {

		iR_ID,err := self.GetInt64("R_ID",0)
		if err != nil{
			self.ajaxMsg(err.Error(), MSG_ERR)
			return	
		}
		iRoomID,err := self.GetInt64("I_RoomID",0)
		if err != nil{
			self.ajaxMsg(err.Error(), MSG_ERR)
			return	
		}
		curdate := libs.GetDateNowString();
		RoomBloodInfo := models.RoomBloodOperate{Rid:iR_ID,
			Status:1,
			DelGid:self.userId,
			DelTime:curdate,
			OpTime:libs.GetCurSysTmeTimeToUnix()}
		err = RoomBloodInfo.Update("Status","DelGid","DelTime","OpTime");
		gmlos := fmt.Sprintf("删除房间【%d】rid= %d 血池控制",iRoomID, iR_ID)
		if nil == err {
			self.AddOperationLog(gmlos,1)
			self.ajaxMsg("" , MSG_OK)
		}else{
			self.AddOperationLog(gmlos,0)
			self.ajaxMsg(err.Error(), MSG_ERR)
		}
		return
	} else if iType == 2{
		Server_ID,err := self.GetInt("Server_ID",0)
		if err != nil{
			self.ajaxMsg(err.Error(), MSG_ERR)
			return	
		}
		Allow_Enter,err := self.GetInt64("Allow_Enter",0)
		if err != nil{
			self.ajaxMsg(err.Error(), MSG_ERR)
			return	
		}
		Rid_id,err := self.GetInt64("r_ID",0)
		if err != nil{
			self.ajaxMsg(err.Error(), MSG_ERR)
			return	
		}
		tmpAllowEnter := 1
		if(Allow_Enter == 1){
			tmpAllowEnter = 0
		}
	
		roomCtrl := models.RoomCtrlInfo{ServerID:Server_ID,
			NType:1,
			AllowEnter:tmpAllowEnter}
		err = roomCtrl.Insert();

		if nil == err {
			roomMain := models.RoomCheatMain{Rid:Rid_id,
				AllowEnter:tmpAllowEnter}
			roomMain.Update(Server_ID,"AllowEnter")

			if tmpAllowEnter == 0 {
				gmlos := fmt.Sprintf("解锁房间【%d】",Server_ID)
				self.AddOperationLog(gmlos,1)
				self.ajaxMsg("解锁成功" , MSG_OK)
			}else{
				gmlos := fmt.Sprintf("锁定房间【%d】",Server_ID)
				self.AddOperationLog(gmlos,1)
				self.ajaxMsg("锁定成功" , MSG_OK)

			}
			
		} else{
			self.ajaxMsg(err.Error(), MSG_ERR)
		}
		return
	}
	self.ajaxMsg("未找到删除类型！" , MSG_ERR)
}

func (self *SysRoomconfController) Table() {
	//列表
	page, err := self.GetInt("page")
	if err != nil {
		page = 1
	}
	limit, err := self.GetInt("limit")
	if err != nil {
		limit = 30
	}
	
	self.pageSize = limit

	roomsysroominfo := self.GetString("sys_room_info")
	sys_today_Win := self.GetString("sys_today_Win")
	
	//fmt.Println(roomsysroominfo,sys_today_Win,page,limit)
	
	//查询条件
	DayTzeroTime := libs.GetUnixZeroTime();
	roomSubinfo,roomIDs := models.RoomCheatSubTodayInfo(DayTzeroTime,sys_today_Win)

	filters := make([]interface{}, 0)
	if roomsysroominfo != "" {
		filters = append(filters, "RoomName__icontains", roomsysroominfo)
	}

	if sys_today_Win != "" {
		if len(roomIDs) > 0{
			filters = append(filters, "RoomID__in",roomIDs)
		} else{
			filters = append(filters, "RoomID__in",-1)	
		}
	}
	result, count := models.RoomCheatMainGetList(page, self.pageSize,filters...)
	
	list := make([]map[string]interface{}, len(result))
	for k, v := range result {
		row := make(map[string]interface{})
		row["Rid"] = v.Rid
		row["ServerID"] = v.RoomID
		row["RoomName"] = v.RoomName
		row["TotalWin"] = v.AllWinLose
		tmpTodayWinLose,tmpTodayLose := models.RoomCheatSubGetTodayDataByRoomID(roomSubinfo,v.RoomID)
		row["TodayWin"] = tmpTodayWinLose
		row["TodayLose"] = tmpTodayLose
		row["TotalLose"] = v.AllUserCheatBloodPool
		row["PoolScore"] = v.RoomAwardPool
		row["BloodBancle"] = v.RoomBloodBalance //beego.Date(time.Unix(v.UpdateTime, 0), "Y-m-d H:i:s")
		row["Bloods"] = v.RoomBloodPool
		row["MuteEatP"] = v.MinusCheatRate
		row["EatP"] = v.EatCheatRate
		row["RoomStatus"] = v.AllowEnter
		row["PukeP"] = v.VomitCheatRate
		row["TaxRate"] = v.TaxRate
		row["RobotCount"] = v.RobotCount
		
		list[k] = row

	}
	self.ajaxList("成功", MSG_OK,count, list)
  
}
func (self *SysRoomconfController) HisEatPukeList() {
	self.Data["pageTitle"] = "房间历史吞吐列表"
	ServerID, _ := self.GetInt("ServerID", 0)
	RoomName := self.GetString("RoomName")
	self.Data["RoomInFoName"] = RoomName
	self.Data["RoomInFoServerID"]  = ServerID
	gmlos := fmt.Sprintf("从【%s(%d)】【%s】界面",RoomName,ServerID,self.Data["pageTitle"] )
	self.AddOperationLog(gmlos,1)
	self.display()
	
}
func (self *SysRoomconfController) HisEtaPutTable(){


	page, err := self.GetInt("page")
	if err != nil {
		page = 1
	}
	limit, err := self.GetInt("limit")
	if err != nil {
		limit = 30
	}
	
	self.pageSize = limit
	
	ServerID, _ := self.GetInt("RoomInFo_ServerID", 0)
	RoomName := self.GetString("RoomInFo_Name")
	befor_date := self.GetString("befor_date")
	after_date := self.GetString("after_date")
	
	self.Data["RoomInFoName"] = RoomName
	self.Data["RoomInFoServerID"]  = ServerID

	//查询条件
	filters := make([]interface{}, 0)
	
	filters = append(filters, "RoomID", ServerID)
	if befor_date != "" {
		befor_dateInt64 :=  libs.GetStringTimeToUnix(befor_date,"Y-m-d");
		filters = append(filters, "UpdateTime__gte", befor_dateInt64)
	}
	if after_date != "" {
		after_dateInt64 := libs.GetStringTimeToUnix(after_date,"Y-m-d");
		filters = append(filters, "UpdateTime__lte", after_dateInt64)
	}
	result, count := models.RoomCheatSubGetList(page, self.pageSize,filters...)
	list := make([]map[string]interface{}, len(result))
	for k, v := range result {
		row := make(map[string]interface{})
		row["UpDataTime"] = beego.Date(time.Unix(v.UpdateTime, 0), "Y-m-d")
		row["SerVerID"] = v.RoomID
		row["RoomName"] =  RoomName
		row["TodayWin"] = v.TodayWinLose
		row["PukeSocretotal"] = v.TodayVomitScore
		row["PukeTimes"] = v.TodayVomitTimes
		row["EateScoreTotal"] = v.TodayEatScore
		row["EatTimes"] = v.TodayEatTimes //beego.Date(time.Unix(v.UpdateTime, 0), "Y-m-d H:i:s")
		row["EatTimePuke"] =  libs.GetTaxRateToSring(v.TodayEatScore,v.TodayVomitScore)
			
		list[k] = row

	}
	gmlos := fmt.Sprintf("查询【%d】从【%s】到【%s】的房间历史吞吐列表",ServerID,befor_date,after_date);
	self.AddOperationLog(gmlos,1)
	self.ajaxList("成功", MSG_OK,count, list)
}
func (self *SysRoomconfController) BloodContrl(){
	self.Data["pageTitle"] = "添加血池房间配置"
	ServerID, _ := self.GetInt("ServerID", 0)
	//RoomName := self.GetString("RoomName")

	self.Data["curServerID"]  = ServerID


	result, _ := models.RoomCheatMainGetAllList()
	list := make([]map[string]interface{}, len(result))
	for k,v := range result {
		row := make(map[string]interface{})
		row["ServerID"] = v.RoomID
		row["RoomName"] = v.RoomName
		list[k] = row
	}
	self.Data["RoomList"] = list
	gmlos := fmt.Sprintf("从【%d】【%s】界面",ServerID,self.Data["pageTitle"]);
	self.AddOperationLog(gmlos,1)
	self.display()
}
func (self *SysRoomconfController) RoomBooldCtrl() {
	iType, err := self.GetInt("Ctrl_Type", 0);
	if err != nil{
		self.ajaxMsg(err.Error(), MSG_ERR);
		return
	}
	//fmt.Println("1111111111111111111111111111111122222221111::::",iType)
	if iType == 1 {
		iRoomID , err := self.GetInt("Room_ID", 0);
		if err != nil{
			self.ajaxMsg(err.Error(), MSG_ERR);
			return;
		}
		i64AddValues,err := self.GetInt64("Add_Values", 0)
		if err != nil{
			self.ajaxMsg(err.Error(), MSG_ERR);
			return;
		}
		self.Data["curServerID"]  = iRoomID
		strOperateDataTime := self.GetString("Ctrl_DataTime");
		bloodoperate := models.RoomBloodOperate{RoomID:iRoomID,
			BloodScore:i64AddValues,
			OperateTime:libs.GetStringTimeToUnix(strOperateDataTime, "Y-m-d H:i:s"),
			Status:0,
			AddGid:self.userId,
			OpTime:libs.GetCurSysTmeTimeToUnix()}
  	   	err = bloodoperate.Insert();
  	   	gmlos := fmt.Sprintf("控制房间【%d】在【%s】加入【%d】血池！",iRoomID,strOperateDataTime,i64AddValues)
    	if err != nil{
    			self.AddOperationLog(gmlos,0)
			self.ajaxMsg(err.Error(), MSG_ERR);
			return
		}
	
		self.AddOperationLog(gmlos,1)
		self.ajaxMsg("修改血池成功！", MSG_OK);
		return
	}else if iType == 2 {
		
			iRoomID, err := self.GetInt("Room_ID", 0);
			if err != nil{
				self.ajaxMsg(err.Error(), MSG_ERR);
				return
			}
			//self.Data["curServerID"]  = iRoomID
			iMinusCheatRate, err := self.GetInt("dMinus_Cheat_Rate", 0);
			if err != nil{
				self.ajaxMsg(err.Error(), MSG_ERR);
				return
			}
			iEatCheatRate, err := self.GetInt("dEat_Cheat_Rate", 0);
			if err != nil{
				self.ajaxMsg(err.Error(), MSG_ERR);
				return
			}	        
			iVomitCheatRate, err := self.GetInt("dVomit_Cheat_Rate", 0);
			if err != nil{
				self.ajaxMsg(err.Error(), MSG_ERR);
				return
			}		  
            iRoomBloodBalance, err := self.GetInt64("dRoom_Blood_Balance", 0);
			if err != nil{
				self.ajaxMsg(err.Error(), MSG_ERR);
				return
			}
            iTaxRate, err := self.GetInt("dTax_Rate", 0);
			if err != nil{
				self.ajaxMsg(err.Error(), MSG_ERR);
				return
			} 

			iRobotCount, err := self.GetInt("dRobot_Count", 0);
			if err != nil{
				self.ajaxMsg(err.Error(), MSG_ERR);
				return
			} 
        	if iMinusCheatRate < -1000 || iMinusCheatRate > 1000 || iEatCheatRate < -1000 || iEatCheatRate > 1000 || iVomitCheatRate < -1000 || iVomitCheatRate > 1000 || iTaxRate < 0 || iTaxRate > 10000 {
        		self.ajaxMsg("参数错误", MSG_ERR);
        		return
        	}

        	roomCtrl := models.RoomCtrlInfo{ServerID:iRoomID,
			NType:0,
			RoomBloodBalance:iRoomBloodBalance,
			MinusCheatRate:iMinusCheatRate,
			EatCheatRate:iEatCheatRate,
			VomitCheatRate:iVomitCheatRate,
			TaxRate:iTaxRate,
			RobotCount:iRobotCount};
			err = roomCtrl.Insert();

			roomMain := models.RoomCheatMain{
				RoomBloodBalance:iRoomBloodBalance,
				MinusCheatRate:iMinusCheatRate,
				EatCheatRate:iEatCheatRate,
				VomitCheatRate:iVomitCheatRate,
				TaxRate:iTaxRate,
				RobotCount:iRobotCount};

			roomMain.Update(iRoomID,"RoomBloodBalance","MinusCheatRate","EatCheatRate","VomitCheatRate","TaxRate","RobotCount");
		
			gmlos := fmt.Sprintf("修改【%d】房间配置为:负分吃分作弊率:%d 吃分作弊率:%d,吐分作弊率:%d,血池平衡值:%d,税率:%d,机器人:%d",iRoomID,iMinusCheatRate,iEatCheatRate,iVomitCheatRate,iRoomBloodBalance,iTaxRate,iRobotCount)
      
			if nil == err  {
				self.AddOperationLog(gmlos,1)
				self.ajaxMsg("修改房间配置成功！", MSG_OK);
				return
			}
			self.AddOperationLog(gmlos,0)
			self.ajaxMsg(err.Error() , MSG_ERR);
			return
	}
	self.ajaxMsg("类型错误！", MSG_ERR);
}

func(self *SysRoomconfController) Bloodcontrlimport(){
	self.Data["pageTitle"] = "血池控制导入"
	self.AddOperationLog(fmt.Sprintf("进入【%s】页面",self.Data["pageTitle"] ),1);
	self.display();



}


func(self * SysRoomconfController) Uploadxls(){
	

	f, h, err := self.GetFile("file")                  //获取上传的文件
	if err == nil {
		fmt.Println(h.Filename);
		path := "./upload/"+ h.Filename  // 文件目录
		f.Close()                                          //关闭上传的文件，不然的话会出现临时文件不能清除的情况
		err :=self.SaveToFile("file", path)                    //存文件  

		if err == nil{
			
			str:=self.SaveXLSdataToMysql(path);
			self.ajaxMsg(str, MSG_OK);
		}else
		{
			self.ajaxMsg(err.Error(), MSG_ERR);
		}
		
	}else
	{
		self.ajaxMsg("获取数据错误！", MSG_ERR);
	}
}

func(self * SysRoomconfController) SaveXLSdataToMysql(path string) string{
	fmt.Println("xlspath====================>>",path)
	xlsx, err := excelize.OpenFile(path)
    if err != nil {
        fmt.Println(err)
        os.Exit(1)
    }
    // Get value from cell by given worksheet name and axis.
    //cell := xlsx.GetCellValue("bloodlist", "B1")
    //fmt.Println(cell)
	// Get all the rows in the Sheet1.
	
	var datalist[] models.RoomBloodOperate;
	var rowERR = "";
    rows := xlsx.GetRows("bloodlist")
    for index, row := range rows {
		fmt.Println(index,"\t",row);
		fmt.Println(row[0],row[1],row[2]);
		if index == 0{
			continue;
		}

		var data models.RoomBloodOperate;
		v,e := strconv.Atoi(row[0]);
		if e == nil{
			data.RoomID = v ;
		}else
		{
			rowERR = rowERR+ strconv.Itoa(index)+",";
			fmt.Println(e.Error());
			continue;
		}
		
		v2,e := strconv.ParseInt(row[1], 10, 64);
		if e == nil{
			data.BloodScore = v2 ;
		}else
		{
			rowERR = rowERR+ strconv.Itoa(index)+",";
			fmt.Println(e.Error());
			continue;
		}

		v3:= beego.StringTimeToUnix(row[2],"2006/01/03 15:04");
		if v3 > 0 {
			data.OperateTime = v3;
		}else
		{
			rowERR = rowERR+ strconv.Itoa(index)+",";
			fmt.Println("时间转换小于0");
			continue;
		}
		
		data.AddGid = self.userId;
		data.OpTime = time.Now().Unix();



		datalist = append(datalist,data);
      
	}
	

	if rowERR == ""{
		models.RoomBloodOperateXLSdata(&datalist);
	}else
	{
		fmt.Println("没导入数据\n",datalist)
	}
	
	return rowERR;
}



func (self *SysRoomconfController) BloodContrlList(){
	self.Data["pageTitle"] = "血池控制列表"
	ServerID, _ := self.GetInt("ServerID", 0)
	//RoomName := self.GetString("RoomName")
	befor_date := self.GetString("Befor_Datetime")
	after_date := self.GetString("After_Datetime")
	cruCrtl_status,_ := self.GetInt("Blood_Ctrlstatus",0)
	self.Data["curServerID"]  = ServerID
	self.Data["befor_date"]  = befor_date
	self.Data["after_date"]  = after_date
	self.Data["cruCrtl_status"]  = cruCrtl_status


	//filters := make([]interface{}, 0)
	result, _ := models.RoomCheatMainGetAllList()

	list := make([]map[string]interface{}, len(result))
	for k,v := range result {
		row := make(map[string]interface{})
		row["ServerID"] = v.RoomID
		row["RoomName"] = v.RoomName
		list[k] = row
	}
	self.Data["RoomList"] = list

	gmlos := fmt.Sprintf("从【%d】【%s】界面",ServerID,self.Data["pageTitle"]);
	self.AddOperationLog(gmlos,1)
	self.display()
}

func (self *SysRoomconfController) BloodContrlListTable() {
	page, err := self.GetInt("page")
	if err != nil {
		page = 1
	}
	limit, err := self.GetInt("limit")
	if err != nil {
		limit = 30
	}
	
	self.pageSize = limit
	
	ServerID, _ := self.GetInt("Room_ID", 0)
	befor_date := self.GetString("Befor_Datetime")
	after_date := self.GetString("After_Datetime")
	cruCrtl_status,_ := self.GetInt("Blood_Ctrlstatus",0)
	self.Data["curServerID"]  = ServerID
	self.Data["befor_date"]  = befor_date
	self.Data["after_date"]  = after_date
	self.Data["cruCrtl_status"]  = cruCrtl_status
	//查询条件

	filters := make([]interface{}, 0)
	if ServerID > 0 {
		filters = append(filters, "RoomID", ServerID)
	}
	roomresult, _ := models.RoomCheatMainGetAllList(filters...)
	if cruCrtl_status > 0 {

		filters = append(filters, "Status", cruCrtl_status-1)
	}

	
	
	if befor_date != "" {
		befor_dateInt64 :=  libs.GetStringTimeToUnix(befor_date,"Y-m-d H:i:s");
		filters = append(filters, "OperateTime__gte", befor_dateInt64)
	}
	if after_date != "" {
		after_dateInt64 := libs.GetStringTimeToUnix(after_date,"Y-m-d H:i:s");
		filters = append(filters, "OperateTime__lte", after_dateInt64)
	}
	
	result, count := models.RoomBloodOperateGetList(page, self.pageSize,filters...)
	list := make([]map[string]interface{}, len(result))
	for k, v := range result {
		row := make(map[string]interface{})
		row["Rid"] = v.Rid;
		row["SerVerID"] = v.RoomID
		row["RoomName"] =  models.GetRoomNameFromRoomInfoByID(roomresult,v.RoomID)
		row["OperateTime"] =  beego.Date(time.Unix(v.OperateTime, 0), "Y-m-d H:i:s")
		row["BloodScore"] = v.BloodScore
		row["Status"] = v.Status
		row["OpTime"] = beego.Date(time.Unix(v.OpTime, 0), "Y-m-d H:i:s")
		
			
		list[k] = row

	}
	gmlos := fmt.Sprintf("查询【%d】从【%s】到【%s】状态是【%d】血池控制列表",ServerID,befor_date,after_date,cruCrtl_status-1);
	self.AddOperationLog(gmlos,1)
	self.ajaxList("成功", MSG_OK,count, list)
}

func (self *SysRoomconfController) ModifyRoomConf(){
	self.Data["pageTitle"] = "修改房间作弊率配置"
	ServerID, _ := self.GetInt("ServerID", 0)
	//RoomName := self.GetString("RoomName")

	self.Data["curServerID"]  = ServerID

	//fmt.Println("---------------************")
	//fmt.Println(ServerID)

	//filters := make([]interface{}, 0)
	result, _ := models.RoomCheatMainGetAllList()

	list := make([]map[string]interface{}, len(result))
	for k,v := range result {
		row := make(map[string]interface{})
		row["ServerID"] = v.RoomID
		row["RoomName"] = v.RoomName
		list[k] = row
	}
	self.Data["RoomList"] = list
	RoomInfo,_ := models.RoomCheatMainGetByRoomID(ServerID)
	self.Data["RoomInfo"] = RoomInfo
	gmlos := fmt.Sprintf("从【%d】【%s】界面",ServerID,self.Data["pageTitle"]);
	self.AddOperationLog(gmlos,1)
	self.display()
}

func (self *SysRoomconfController) BloodChangeList(){
	self.Data["pageTitle"] = "房间血池变化"
	ServerID, _ := self.GetInt("ServerID", 0)
	
	self.Data["curServerID"]  = ServerID

	result, _ := models.RoomCheatMainGetAllList()

	list := make([]map[string]interface{}, len(result))
	for k,v := range result {
		row := make(map[string]interface{})
		row["ServerID"] = v.RoomID
		row["RoomName"] = v.RoomName
		list[k] = row
	}
	self.Data["RoomList"] = list
	
	gmlos := fmt.Sprintf("从【%d】【%s】面",ServerID,self.Data["pageTitle"]);
	self.AddOperationLog(gmlos,1)
	self.display()
}


func (self *SysRoomconfController) BloodChangeTable(){
//go func() {
		//xMutex := libs.GetxMutex();
	 	//xMutex.XMutexLock();
		ServerID, err := self.GetInt("room_ID", 0)
		if err != nil {
			self.ajaxList("成功", MSG_OK,0, nil)
			return;
		}
		beforDateTime := self.GetString("befor_DataTime");
		afterDateTime := self.GetString("after_DataTime");
		i64beforDateTime := libs.GetStringTimeToUnix(beforDateTime,"Y-m-d H:i:s");
		i64afterDateTime := libs.GetStringTimeToUnix(afterDateTime,"Y-m-d H:i:s");
		//fmt.Println(ServerID,berorDateTime,beForDateTime)


		filters := make([]interface{}, 0);
		
		filters = append(filters, "ServerID", ServerID);

		filters = append(filters, "WriteDateTime__gte",i64beforDateTime);

		filters = append(filters, "WriteDateTime__lte",i64afterDateTime)	;

		result, count := models.RoomBloodChangeGetAllList(filters...);
		list := make([]map[string]interface{}, len(result));
		for k, v := range result {
			row := make(map[string]interface{});
			row["datetimes"] = beego.Date(time.Unix(v.WriteDateTime, 0), "Y-m-d H:i:s");
			row["RoomBloods"] = v.BloodScore;
			row["RoomBloodBalance"] = v.RoomBloodBalance;
			list[k] = row

		}
		gmlos := fmt.Sprintf("查询【%d】从【%s】到【%s】的血池变化",ServerID,beforDateTime,afterDateTime);
		self.AddOperationLog(gmlos,1)
		self.ajaxList("成功", MSG_OK,count, list)
		//defer xMutex.XMutexUnLock();
	//}()
}
